<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="vue.js"></script>
</head>
<body>
    <div id="app">
        <h2>{{msg}}</h2>
        <div>
            <table>
                <tr>
                    <th>名称</th>
                    <th>单价<button @click="up">↑</button><button @click="down">↓</button></th>
                    <th>数量</th>
                    <th>合计</th>
                </tr>
                <tr v-for="(item,index) in goodsInfo">
                    <td>{{item.name}}</td>
                    <td>{{item.price}}</td>
                    <td><button @click="add(item,index)"></button>{{item.num}}<button @click="sub(item,index)"></button></td>
                    <td>{{item.price*item.num}}</td>
                </tr>
            </table>
            <p>总金额:{{goodsPriceTotal}}</p>
            <hr>
            <input type="checkbox" v-model="checkin">使用8折优惠券:-{{this.checkin ? goodsPriceTotal*0.2 : 0}}
            <hr>
            <strong>合计:</strong>{{this.checkin ? goodsPriceTotal*0.8 : goodsPriceTotal}}
            <hr>
            <input type="text" v-model="addGood.name" value="请输入商品">
            <input type="text" v-model="addGood.price" value="请输入商品">
            <button @click="addGoods">添加商品</button>
        </div>
    </div>
    <script>
        new Vue({
            msg:'购物车',
            el:'#app',
            data:{
                goodsInfo:[
                    {name:'iphone',price:5000,num:1},
                    {name:'dell笔记本',price:4000,num:1},
                    {name:'mi',price:2000,num:1}
                ],
                checkin:false,
                addGood:{},

            },
            computed:{
                goodsPriceTotal(){
                    let total = 0
                    for(let item of this.goodsInfo){
                        total += item.price * item.num
                    }
                    return total
                }

            },
            methods:{
                add(item,index){
                    this.goodsInfo[index].num=item.num+1
                },
                sub(item,index){
                    if(item==0)
                        return
                    else
                        this.goodsInfo[index].num=item.num-1
                },
                up(){
                    this.goodsInfo.sort(function(a,b){
                        return a.price-b.price
                    })
                },
                down(){
                    this.goodsInfo.sort(function(a,b){
                        return b.price-a.price
                    })
                },
                addGoods(){
                    this.goodsInfo.push({...this.addGood,num:1})
                    this.addGood={}
                }
            },
        })
    </script>
</body>
</html>